package com.yht.redbookauth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.yht.framework.common.exception.BizException;
import com.yht.framework.common.response.Response;
import com.yht.redbookauth.constant.RedisKeyConstants;
import com.yht.redbookauth.enums.ResponseCodeEnum;
import com.yht.redbookauth.model.vo.verificationcode.SendVerificationCodeReqVO;
import com.yht.redbookauth.service.VerificationCodeService;
import com.yht.redbookauth.sms.AliyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    /**
     * 发送短信
     *
     * @param sendVerificationCodeReqVO
     * @return
     */
    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {

        // 手机号
        String phone = sendVerificationCodeReqVO.getPhone();

        //构建存储在 redis 中验证码的key
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);

        //判断key是否存在，若存在则报错 请求频繁...
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }

        //随机生成6位验证码
        String verificationCode = RandomUtil.randomNumbers(6);

        log.info("===>手机号： {}， 已发送验证码：{}", phone, verificationCode);

        // 调用第三方服务发送短信
        threadPoolTaskExecutor.submit(() -> {
            String signName = "阿里云短信测试";
            String templateCode = "SMS_154950909";
            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        });

        //存储验证码
        redisTemplate.opsForValue().set(key, verificationCode, 3, TimeUnit.MINUTES);

        return Response.success();
    }
}
